package com.smarthome.api.mobile.service;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.smarthome.api.ipc.IpcCommandService;
import com.smarthome.api.mobile.util.IpcUrlUtil;
import com.smarthome.common.mobile.Service;
import com.smarthome.core.deviceManager.EquipmentDevIpcService;
import com.smarthome.core.deviceManager.EquipmentDevSwingService;
import com.smarthome.core.deviceManager.EquipmentDevTalkService;
import com.smarthome.core.workingmonitor.EquipmentCommLogService;
import com.smarthome.domain.bean.ShEquipmentCommLog;
import com.smarthome.domain.bean.ShEquipmentDevSwing;
import com.smarthome.domain.bean.ShEquipmentDevTalk;
import com.smarthome.domain.enums.EquipmentTypeEnum;
import com.smarthome.domain.mobile.MobileCodeEnum;
import com.smarthome.domain.mobile.MobileResponse;
import com.smarthome.domain.mobile.req.MobileComdeviceOpenRequest;

@org.springframework.stereotype.Service("mobile.comdevice.service")
public class MobileComDeviceOpenService implements Service<MobileResponse<?>> {

    @Resource
    private IpcCommandService ipcCommandService;

    @Resource
    private EquipmentDevSwingService equipmentDevSwingService;

    @Resource
    private EquipmentDevTalkService equipmentDevTalkService;

    @Resource
    private EquipmentDevIpcService equipmentDevIpcService;
    @Resource
    private EquipmentCommLogService equipmentCommLogService;
    private static Logger logger = Logger.getLogger(MobileComDeviceOpenService.class);

    /**
     * 摆闸开门
     * @param request
     * @param response
     */
    public void openResidenceSwing(MobileComdeviceOpenRequest request, MobileResponse<?> response) {
        Long deviceId = request.getDeviceId();
        if (null == deviceId) {
            response.setMobileCodeObj(MobileCodeEnum.DEVICE_NO_ID);
        } else {
            ShEquipmentDevSwing swing = equipmentDevSwingService.queryById(deviceId);
            if (null == swing) {
                response.setMobileCodeObj(MobileCodeEnum.DEVICE_NO_INFO);
            } else {
                String ipcUrl = formatIpcUrl(swing.getIpcIp(), swing.getIpcPort());
                String command = IpcUrlUtil.SWING_COMMAND;
                String method = IpcUrlUtil.SWING_OPEN_METHOD;
                Map<String, String> params = new HashMap<String, String>();
                params.put("ip", swing.getLocalIp());
                params.put("deviceId", swing.getId() + "");
                params.put("accessType", "localnetwork");
                logger.info("start-open-door");
                MobileCodeEnum res = getBackEnum(ipcUrl, command, method, params);
                logger.info("end-open-door");
                ShEquipmentCommLog equipmentCommLog = new ShEquipmentCommLog();
                equipmentCommLog.setEquipmentId(deviceId);
                equipmentCommLog.setEquipmentType(EquipmentTypeEnum.DEV_SWING.getCode());
                equipmentCommLog.setEquipmentName(swing.getName());
                equipmentCommLog.setRequestMsg(params.toString());
                equipmentCommLog.setResponseMsg(res.getMsg());
                equipmentCommLog.setResidenceId(swing.getResidenceId());
                equipmentCommLog.setResidenceName(swing.getResidenceName());
                logger.info("save-open-door-log");
                equipmentCommLogService.saveLog(equipmentCommLog);
                response.setMobileCodeObj(res);
            }
        }
    }

    /**
     * 门口机开门
     * @param request
     * @param response
     */
    public void openUnitTalk(MobileComdeviceOpenRequest request, MobileResponse<?> response) {
        Long deviceId = request.getDeviceId();
        if (null == deviceId) {
            response.setMobileCodeObj(MobileCodeEnum.DEVICE_NO_ID);
        } else {
            ShEquipmentDevTalk talk = equipmentDevTalkService.queryById(deviceId);
            if (null == talk) {
                response.setMobileCodeObj(MobileCodeEnum.DEVICE_NO_INFO);
            } else {
                String ipcUrl = formatIpcUrl(talk.getIpcIp(), talk.getIpcPort());
                String command = IpcUrlUtil.TALK_COMMAND;
                String method = IpcUrlUtil.TALK_OPEN_METHOD;
                Map<String, String> params = new HashMap<String, String>();
                params.put("ip", talk.getLocalIp());
                params.put("port", talk.getLocalPort());
                MobileCodeEnum res = getBackEnum(ipcUrl, command, method, params);
                response.setMobileCodeObj(res);

            }
        }
    }

    private MobileCodeEnum getBackEnum(String ipcUrl, String command, String method, Map<String, String> params) {
        MobileCodeEnum res = MobileCodeEnum.COMMON_SUCCESS;
        String back = ipcCommandService.sendCommand(ipcUrl, command, method, params);
        if (null == back) {
            res = MobileCodeEnum.DEVICE_FAIL_DO;
        } else {
            try {
                JSONObject object = (JSONObject) JSONObject.parse(back);
                String code = object.getString("code");
                if (!"ok".equals(code)) {
                    res = MobileCodeEnum.DEVICE_FAIL_DO;
                }
            } catch (Exception e) {
                e.printStackTrace();
                res = MobileCodeEnum.SYSTEM_ERROR;
            }

        }
        return res;
    }

    private String formatIpcUrl(String ip, String port) {
        StringBuilder ipcUrl = new StringBuilder("http://");
        ipcUrl.append(ip + ":" + port);
        ipcUrl.append("/ipc/gateway.do");
        return ipcUrl.toString();
    }
}
